package com.seelyn.rhea.mvc.render.provider;

import com.seelyn.rhea.mvc.common.utils.GsonUtils;
import com.seelyn.rhea.mvc.context.Request;
import com.seelyn.rhea.mvc.context.Response;
import com.seelyn.rhea.mvc.render.Render;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author linfeng
 * @since 2016/1/21
 */
public class JsonRender implements Render<JsonView> {

    private static final Logger logger = LoggerFactory.getLogger(JsonRender.class);

    @Override
    public void render(JsonView jsonView, Request request, Response response) {
        response.type(jsonView.getContentType());
        response.raw().setCharacterEncoding("UTF-8");
        response.raw().setContentType(jsonView.getContentType());
        String jsonStr = GsonUtils.getInstance().toJson(jsonView.getContent());
        PrintWriter out = null;
        try {
            out = response.raw().getWriter();
            out.write(jsonStr);
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
